package com.example.stack.utils;

import com.example.stack.constant.AccountConstant;

import java.util.concurrent.TimeUnit;

public class BankNumberUtil {

    /**
     * 生成银行卡号
     * @return  银行卡号
     */
    public synchronized static String getBankNumber() {
        try {
            TimeUnit.MICROSECONDS.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String old = AccountConstant.ACCOUNT_PREFIX + getUnixTime();
        return old + getBankCardCheckCode(old);
    }


    /***
     * 获取当前系统时间戳 并截取
     * @return 时间戳
     */
    private static String getUnixTime() {
        String time = "";
        time = (((System.currentTimeMillis()) + "").substring(4));
        return time;
    }

    /**
     * 校验银行卡卡号
     *
     * @param cardId 银行卡号
     * @return ture校验成功，false校验失败
     */
    public static boolean checkBankCard(String cardId) {
        char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
     *
     */
    public static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if (nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            //如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 1; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }


}
